package com.example.config.auth;

import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.time.Instant;
import java.util.*;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Slf4j
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter implements InitializingBean {


    private List<String> IGNORE_URLS=new ArrayList<>();

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/doc.html",
                        "/index.html",
                        "/web/**",
                        "/swagger-resources/**",
                        "/v2/**","/webjars/**",
                        "/Hystrix/**")
                .permitAll()
                .antMatchers(IGNORE_URLS.toArray(new String[IGNORE_URLS.size()])).permitAll()
                .antMatchers("/**").authenticated(); // 配置order访问控制，必须认证后才可以访问
    }



    @Autowired
    private WebApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        map.keySet().forEach(info -> {

            HandlerMethod handlerMethod = map.get(info);
            // 获取方法上边的注解 替代path variable 为 *
            IsAuth method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), IsAuth.class);
            if(method != null && !method.isSecurity()){
                Optional.of(method)
                        .ifPresent(inner -> info.getPatternsCondition().getPatterns()
                                .forEach(url ->{
                                    url=url.replaceAll("\\{(.*?)\\}","**");
                                    log.info("path {} 系统将不会做拦截",url);
                                    IGNORE_URLS.add(url);
                                }));
            }
            // 获取类上边的注解, 替代path variable 为 *
            IsAuth controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), IsAuth.class);
            if(controller != null && !controller.isSecurity()){
                Optional.of(controller)
                        .ifPresent(inner -> info.getPatternsCondition().getPatterns()
                                .forEach(url -> {
                                    url=url.replaceAll("\\{(.*?)\\}","**");
                                    log.info("path {} 系统将不会做拦截",url);
                                    IGNORE_URLS.add(url);
                                }));
            }
        });
    }
}
